package org.beholder;


import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * Created by IntelliJ IDEA.
 * User: ddreval
 * Date: 02.10.12
 * Time: 18:39
 * To change this template use File | Settings | File Templates.
 */
public class AbstractServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private Logger logger = Logger.getLogger(AbstractServlet.class);

    protected Connection conn;

    @Override
    public void init() throws ServletException {

    	super.init();

    	try {
    		System.out.println("Setting Logger properties");
        	Properties properties = new Properties();
        	properties.setProperty("log4j.appender.file", "org.apache.log4j.FileAppender");
        	properties.setProperty("log4j.appender.file.layout", "org.apache.log4j.PatternLayout");
        	properties.setProperty("log4j.appender.file.layout.ConversionPattern", "%d{MMM dd HH:mm:ss,SSS} %-5p [%t] %c{2} - %m%n");
        	properties.setProperty("log4j.appender.file.File", "beholder.log");
        	properties.setProperty("log4j.appender.file.Append", "false");
        	properties.setProperty("log4j.rootLogger", "INFO, file");
        	properties.setProperty("log4j.logger.org.beholder", "TRACE");
            PropertyConfigurator.configure(properties);
            System.out.println("Logger properties set");
        } catch (Exception e) {
        	e.printStackTrace();
        }

        try {
            InitialContext initialContext = new InitialContext();
            DataSource dataSource = (DataSource)initialContext.lookup("java:/comp/env/jdbc/BeholderDB");
            conn = dataSource.getConnection();
            logger.info("Database connection created");
        } catch (NamingException ne) {
            logger.error(ne, ne);
        } catch (SQLException se) {
            logger.error(se, se);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        try {
        	if (conn == null || conn.isClosed()) {
        		logger.debug("Connection is already closed");	
        	} else {
        		conn.close();	
        		logger.debug("Connection closed");        		
        	}
        } catch (SQLException e) {
            logger.error("Failed to close connection", e);
        }
    }

}
